<?php
namespace app\models;

use Yii;
use yii\web\NotFoundHttpException;

class File
{
	/*
	* 存储文件目录
	*/
	public static $saveDir = "../../upload/" ;
	
	public static function saveAttach($id,$file,$customName)
	{
		$connection = Yii::$app->db;
	    
		$name = $file['name'];
		$index = strripos($name, ".");
		if($index)
		{
			$type = substr($name, $index);
		}
		else
		{
			$type = '';
		}

		$folderName = date("Ymd");
		$saveName = date("YmdHis") . rand(1000,9999) . $type;

		if(!is_dir(self::$saveDir . $folderName))
		{
			mkdir(self::$saveDir . $folderName , 0777, true); 
		}

		$path = self::$saveDir . $folderName . "/" .$saveName;
		if(move_uploaded_file($file['tmp_name'], $path))
		{
			if(trim($customName) == "")
			{
				$customName = $name;
			}
			$filepath = "upload/".$folderName."/".$saveName;
			$sql = "INSERT INTO tbl_attachment(articleid,filename,filepath,fileoriginalname) VALUES($id,'$saveName','$filepath','$customName')";
			$connection->createCommand($sql)->execute();

			self::addFileToIndexServer($id,$filepath);
		}
		else
		{
			throw new NotFoundHttpException("文件保存失败");
		}
	}

	public static function delAttachment($id)
	{
		$connection = Yii::$app->db;
		$file = $connection->createCommand("SELECT filepath FROM tbl_attachment WHERE id = $id")->queryOne();
		if($file)
		{
			$filepath = "../../".$file['filepath'];
			if(is_file($filepath))
				unlink($filepath);
		}
	}

	private static function addFileToIndexServer($articleid, $filepath){

		if (empty($articleid) || empty($filepath))
			return;
		$uploadedfileFullPath = "C:/wamp/www/".$filepath;
		$url = "http://localhost:8983/solr/cmf/update/extract?literal.id=".$articleid."&commit=true";
		self::postFileToSolrServer($url,$uploadedfileFullPath);
	}

	private static function postFileToSolrServer($url,$file){
		//Post 1-n files, each element of $files array assumed to be absolute
		// path to a file.  $files can be array (multiple) or string (one file).
		// Data will be posted in a series of POST vars named $file0, $file1...
		// $fileN


		$data['file'] = new \CURLFile($file);

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $url );
		curl_setopt($ch, CURLOPT_POST, 1 );
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data );

		curl_exec( $ch );

		if ($error = curl_error($ch) ) {
			die($error);
		}
		curl_close($ch);

	}
}

?>